//
//  gongju.m
//  afn
//
//  Created by mac on 2018/4/13.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "gongju.h"
#import "ZKImgRunLoopView.h"//轮播器

@implementation gongju

+(void)AFNPOSTDataUrl:(NSString *)url
              andDic:(NSDictionary *)dic
        andTableView:(UITableView *)tableview
             andView:(UIView *)view
     andSuccessBlock:(void(^)(id responseObject))responseObjectBlock
       anderrorBlock:(void(^)(void))errorBlock{
    
    //如果正在上下拉刷新 就不显示
    if([tableview.mj_header isRefreshing]==NO&&[tableview.mj_footer isRefreshing]==NO)
    {
        
        if(view!=nil)
        {
            
            [MBProgressHUD showHUDAddedTo:view animated:YES];
        }
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer setHTTPShouldHandleCookies:YES];//默认是ye
    
    
    
    if ([url containsString:@"html"]) {
//        manager.requestSerializer   = [AFJSONRequestSerializer serializer];
//        manager.responseSerializer= [AFJSONResponseSerializer serializer];
        url= [NSString stringWithFormat:@"%@/%@",_addressUrl,url];
    }
    else{
        
        url= [NSString stringWithFormat:@"%@/%@",_addressUrl2,url];
    }
    
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];

    [manager POST:url  parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{

            //打印接口地址和参数 和返回的参数
            NSLog(@"\n接口调用成功___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的参数%@",_addressUrl2,url,dic,[[responseObject description] kdtk_stringByReplaceingUnicode]);
            
          
            
            [MBProgressHUD hideHUDForView:view animated:YES];
            
            [tableview.mj_header endRefreshing];
            
            [tableview.mj_footer endRefreshing];
            BaseModel *dataModel;
            
            NSDictionary *typedic=[responseObject objectForKey:@"error"];
            if (typedic==nil) {
                 dataModel = [BaseModel mj_objectWithKeyValues:responseObject];
            }else{
               dataModel = [BaseModel mj_objectWithKeyValues:[responseObject objectForKey:@"error"]];
            }
            

            
            if (dataModel.code==100) {
                if(responseObjectBlock!=nil)
                {
                    
                    responseObjectBlock([responseObject objectForKey:@"user"]);
                }
            }else{

                [self svpInfo:dataModel.msg];
            }

            
            
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
            [MBProgressHUD hideHUDForView:view animated:YES];
            
            [tableview.mj_header endRefreshing];
            
            [tableview.mj_footer endRefreshing];
            
            //打印接口地址和参数 和返回的参数
            NSLog(@"\n报错___\n根地址___%@\n接口:%@  \n返回的失败原因%@",_addressUrl,url,error);
            
            
            [FTToastIndicator dismiss];
            
            [gongju svpInfo:@"网络连接失败"];  
            
            if(errorBlock!=nil)
            {
                errorBlock();
            }
            
        });
    }];
    
}

+(void)AFNGETDataUrl:(NSString *)url
              andDic:(NSDictionary *)dic
        andTableView:(UITableView *)tableview
             andView:(UIView *)view
     andSuccessBlock:(void(^)(id responseObject))responseObjectBlock
       anderrorBlock:(void(^)(void))errorBlock{
    
    //如果正在上下拉刷新 就不显示
    if([tableview.mj_header isRefreshing]==NO&&[tableview.mj_footer isRefreshing]==NO)
    {
        
        if(view!=nil)
        {
            
            [MBProgressHUD showHUDAddedTo:view animated:YES];
        }
    }
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/plain", nil];
    
    if ([url containsString:@"sms/get_code"]) {
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
    
//    manager.requestSerializer   = [AFJSONRequestSerializer serializer];
//    manager.responseSerializer= [AFJSONResponseSerializer serializer];


    [manager GET:[NSString stringWithFormat:@"%@/%@",_addressUrl2,url]  parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //打印接口地址和参数 和返回的参数
            NSLog(@"\n接口调用成功___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的参数%@",_addressUrl2,url,dic,[[responseObject description] kdtk_stringByReplaceingUnicode]);
            
            [MBProgressHUD hideHUDForView:view animated:YES];
            
            [tableview.mj_header endRefreshing];
            
            [tableview.mj_footer endRefreshing];
            
//            BaseModel *dataModel = [BaseModel mj_objectWithKeyValues:responseObject];
            
//            if (dataModel.status) {
//                if(responseObjectBlock!=nil)
//                {
//
                    responseObjectBlock(responseObject);
//                }
//            }
//            else{
//                [gongju svpInfo:dataModel.code];
//                return ;
//            }
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:view animated:YES];
            
            [tableview.mj_header endRefreshing];
            
            [tableview.mj_footer endRefreshing];
            
            //打印接口地址和参数 和返回的参数
            NSLog(@"\n报错___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的失败原因%@",_addressUrl2,url,dic,error);
            
            
            [FTToastIndicator dismiss];
            
//            [gongju svpInfo:@"网络连接失败"];
            
            if(errorBlock!=nil)
            {
                errorBlock();
            }
            
        });
    }];
}

+ (void)afnPostImageWithDict:(NSDictionary *)dict WithAddressUrl:(NSString *)addressUrl  withImageArr:(NSArray *)imageArr withFileName:(NSString *)fileName  fileOrImg:(NSString *)Str WithViewController:(UIViewController *)viewController   success:(void(^)(id responseObject))responseObjectBlock{
    

    //菊花
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:viewController.view animated:YES];
    
    hud.mode = MBProgressHUDModeIndeterminate;
    
    [hud showAnimated:YES];
    
    
    
    
   
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain", @"text/json", @"text/javascript", @"text/html", nil];
    
    [manager.requestSerializer setHTTPShouldHandleCookies:YES];//默认是yes
    [manager.securityPolicy setAllowInvalidCertificates:YES];
    
    [manager POST:[NSString stringWithFormat:@"%@/%@",_addressUrl,addressUrl] parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        
        if ([Str isEqualToString:@"img"]) {
            //这个就是流参数
            // 传图片
            for (int x=0; x<imageArr.count; x++) {
                
                
                UIImage *image = imageArr[x];
                
                NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
                
                if(imageData==nil)
                {
                    imageData = UIImagePNGRepresentation(image);
                }
                
                [formData appendPartWithFileData:imageData name:fileName fileName:[NSString stringWithFormat:@"%@%d.png",[self curTimeString],0] mimeType:@"image/png"];
                
            }
        }
        else if ([Str isEqualToString:@"image"]) {
            //这个就是流参数
            // 传图片
            for (int x=0; x<imageArr.count; x++) {
                
                NSDictionary *typeDic=imageArr[x];
                
                UIImage *image = [typeDic objectForKey:@"image"];
                
                NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
                
                if(imageData==nil)
                {
                    imageData = UIImagePNGRepresentation(image);
                }
                NSString *fileName2=[typeDic objectForKey:@"fileName"];
                
                NSString *fileName3=[typeDic objectForKey:@"name"];
                
                [formData appendPartWithFileData:imageData name:fileName2 fileName:fileName3 mimeType:@"image/png"];
                
            }
        }
        else{
            NSString * Name = [NSString stringWithFormat:@"video.mp3"];
            // 上传fileName
            // 转成二进制
            NSString *image = imageArr[0];
            NSData *imageData = [NSData dataWithContentsOfFile:image];
            
            
            
            [formData appendPartWithFileData:imageData name:fileName fileName:Name mimeType:@"amr/mp3/wmr/wav"];
        }
        
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSLog(@"\n接口调用成功___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的参数%@",_addressUrl,addressUrl,dict,[[responseObject description] kdtk_stringByReplaceingUnicode]);
        
        
        [MBProgressHUD hideHUDForView:viewController.view animated:YES];
        
        BaseModel *dataModel = [BaseModel mj_objectWithKeyValues:responseObject];
      
        NSDictionary *typedic=[responseObject objectForKey:@"error"];
        if (typedic==nil) {
            dataModel = [BaseModel mj_objectWithKeyValues:responseObject];
        }else{
            dataModel = [BaseModel mj_objectWithKeyValues:[responseObject objectForKey:@"error"]];
        }
        
        
        
        if (dataModel.code==100) {
            if(responseObjectBlock!=nil)
            {
                
                responseObjectBlock(responseObject);
                [self svpInfo:dataModel.msg];
            }
        }else{
            
            [self svpInfo:dataModel.msg];
        }
        
        
    }  failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        [MBProgressHUD hideHUDForView:viewController.view animated:YES];
        
        //打印接口地址和参数 和返回的参数
        NSLog(@"\n报错___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的参数%@",_addressUrl,addressUrl,dict,error);
        
        [FTToastIndicator dismiss];
        
        [self svpInfo:@"网络连接失败"];
        
        
    }];
    
    
    
    
}



+ (void)getHederImage :(UIViewContentMode )contentMode :(CGRect)rect :(NSArray*)imageUrlArr :(CGFloat)fenYeheight :(UIView *)rootView :(void(^)(int value)) block
{
    
    //网络图片happendTime
    //网络图片
    
    
    
    
    ZKImgRunLoopView *imgRunView = [[ZKImgRunLoopView alloc] initWithFrame:rect fenYeheight:fenYeheight placeholderImg:_zhanweiImageData];
    imgRunView.imgUrlArray =imageUrlArr;
    [rootView addSubview:imgRunView];
    
    imgRunView.contentMode=contentMode;
    [imgRunView  touchImageIndexBlock:^(NSInteger index) {
        
        if(block!=nil)
        {
            block((int)index);
        }
    }];
    
}


#pragma mark————————svp提醒
+ (void)svpInfo:(NSString *)title
{
    Toast *toast = [Toast toast]; //创建一个toast
    [toast makeText:title]; //显示
}

+(NSString*)encodeString:(NSString*)unencodedString{
    
    NSString *str=@"";
    NSArray *array = [unencodedString componentsSeparatedByString:@" "];
    for (int i=0;i<array.count; i++) {
        if (i==0) {
            str= [array[i] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
        else{
            str=[NSString stringWithFormat:@"%@+%@",str,[array[i]  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    
    return str;
}

//判断字符是否为空
+(BOOL)charIsNil:(NSString *)str{
    
    if ([str isKindOfClass:[NSNull class]]||[str isEqualToString:@""]||str==nil) {
        return YES;
    }
    return  NO;
}

#pragma mark————————————————得到当前时间搓 转 时间搓
+ (NSString *)NSDateToTimeCuo
{
    
    NSDate *date=[NSDate new];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    
    return timeSp;
}
#pragma mark———————————————— 计算文字宽度
+ (CGSize)getNSStringWeight:(NSString *)string andViewWight:(CGFloat)height andFont:(NSInteger)font
{
    
    
    return  [string sizeOfTextWithMaxSize:CGSizeMake(MAXFLOAT, height) font:[UIFont systemFontOfSize:font]];
    
}

#pragma mark———————————————— 计算文字高度
+ (CGSize)getNSStringSize:(NSString *)string andViewWight:(CGFloat)weight andFont:(NSInteger)font
{
    
    
    return  [string sizeOfTextWithMaxSize:CGSizeMake(weight, MAXFLOAT) font:[UIFont systemFontOfSize:font]];
    
}
#pragma mark———————————————— 跳转 push
+ (void)pushNextViewController:(UIViewController *)nextViewController andRootController:(UIViewController *)rootVc
{
    
    
    rootVc.hidesBottomBarWhenPushed = YES;
    
    [nextViewController.navigationController pushViewController:rootVc
                                                       animated:YES];
    
}

#pragma mark——————————————获取当前版本号
+ (NSString *)getAPPBanben
{
    
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}

#pragma mark——————————————网络判断
+(void)monitorNetworking
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
            NSLog(@"有网");
        }else{
            SGAlertView *alertView = [SGAlertView alertViewWithTitle:@"⚠️ 警告" delegate:nil contentTitle:@"请去-> [设置 - 蜂窝移动网络 ] 开启数据" alertViewBottomViewType:(SGAlertViewBottomViewTypeOne)];
            [alertView show];
        }
    }];
}

+(void)ToLoging:(UIViewController *)controller{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"" message:@"你还未登录请前往登录" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleDefault   handler:^(UIAlertAction * action) {
         
    }];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault  handler:^(UIAlertAction * action) {
        _loginWithVc(controller);
    }];
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [controller presentViewController:alert animated:YES completion:nil];
}

//手机号码
+ (BOOL)isMobileNumber:(NSString *)mobileNum {
    NSString *target = @"^(0|86|17951)?(13[0-9]|15[012356789]|16[6]|19[89]]|17[01345678]|18[0-9]|14[579])[0-9]{8}$";
    NSPredicate *targetPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", target];
    if ([targetPredicate evaluateWithObject:mobileNum]) {
        return YES;
    }
    
    return NO;
}


+(NSString *)curTimeString
{
    NSDateFormatter *formater = [[ NSDateFormatter alloc] init];
    NSDate *curDate = [NSDate date];//获取当前日期
    [formater setDateFormat:@"yyyyMMddHHmmssss"];//这里去掉 具体时间 保留日期
    NSString * curTime = [formater stringFromDate:curDate];
    
    NSLog(@"%@",curTime);
    
    return curTime;
}


@end
